﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using WickedFlame.Core;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using WickedFlame.Util.Data;

namespace WickedFlame.Util.Actions
{
    public enum SaveType
    {
        Save,
        SaveAs
    }

    public class ExportToFileAction
    {
        Window owner;

        bool error = false;
        public bool Error
        {
            get
            {
                return error;
            }
        }

        public bool DoAction(Window owner, VectorImage image, SaveType type)
        {
            this.owner = owner;

            string newFileName = "";
            try
            {
                newFileName = image.FileName.Substring(image.FileName.LastIndexOf('\\') + 1);
            }
            catch { }

            string newFileDir = image.Path;

            string ending = "";
            try
            {
                ending = newFileName.Substring(newFileName.LastIndexOf('.'));
            }
            catch { }

            if (string.IsNullOrEmpty(ending))
                ending = ".vec";

            Microsoft.Win32.SaveFileDialog saveFileDialog1 = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog1.FileName = newFileName; // Default file name
            saveFileDialog1.Filter = "VecDraw files (.vec)|*.vec|Png (.png)|*.png|Jpeg (.jpg)|*.jpg|Svg (.svg)|*.svg";
            //saveFileDialog1.AddExtension = true;
            switch (ending)
            {
                case ".png":
                    saveFileDialog1.FilterIndex = 2;
                    break;
                case ".jpg":
                    saveFileDialog1.FilterIndex = 3;
                    break;
                case ".svg":
                    saveFileDialog1.FilterIndex = 4;
                    break;
                default:
                    saveFileDialog1.FilterIndex = 1;
                    break;
            }

            // Default file extension
            saveFileDialog1.DefaultExt = ending; 

            if ((type == SaveType.SaveAs) ||
                string.IsNullOrEmpty(newFileName))
            {

                if (!string.IsNullOrEmpty(newFileName))
                {
                    saveFileDialog1.InitialDirectory = newFileDir;
                    saveFileDialog1.FileName = Path.GetFileName(newFileName);
                }
                else
                {
                    saveFileDialog1.InitialDirectory = newFileDir;
                    saveFileDialog1.FileName = "Untitled";
                }

                Nullable<bool> result = saveFileDialog1.ShowDialog(this.owner);

                if (result == false)
                    return false;

                string filename = saveFileDialog1.FileName + ".vec";

                newFileName = saveFileDialog1.FileName;
                newFileDir = new FileInfo(newFileName).DirectoryName;
            }
            else
                newFileName = image.FileName;

            // Write the data
            try
            {
                using (Stream stream = new FileStream(newFileName, FileMode.Create, FileAccess.Write))
                {
                    // Serialize object to text format
                    IFormatter formatter = new BinaryFormatter();

                    switch (newFileName.Substring(newFileName.LastIndexOf('.')))
                    {
                        case ".png":
                            var png = new PngFileFormat();
                            png.Export(image.DrawingCanvas, stream);
                            break;
                        case ".jpg":
                            var jpg = new JpegFileFormat();
                            jpg.Export(image.DrawingCanvas, stream);
                            break;
                        case ".vec":
                            var vec = new VecFileFormat();
                            vec.Export(image.DrawingCanvas, stream);
                            break;
                        case ".svg":
                            var svg = new SvgFileFormat();
                            svg.Export(image.DrawingCanvas, stream);
                            break;
                    }

                }
            }
            catch (ArgumentNullException ex) { return HandleSaveException(ex, newFileName); }
            catch (ArgumentOutOfRangeException ex) { return HandleSaveException(ex, newFileName); }
            catch (ArgumentException ex) { return HandleSaveException(ex, newFileName); }
            catch (System.Security.SecurityException ex) { return HandleSaveException(ex, newFileName); }
            catch (FileNotFoundException ex) { return HandleSaveException(ex, newFileName); }
            catch (DirectoryNotFoundException ex) { return HandleSaveException(ex, newFileName); }
            catch (PathTooLongException ex) { return HandleSaveException(ex, newFileName); }
            catch (IOException ex) { return HandleSaveException(ex, newFileName); }

            // Clear the dirty bit, cache the new file name
            // and the caption is set automatically
            image.FileName = newFileName;
            image.Path = newFileDir;
            image.IsDirty = false;
            image.IsUnwrittenCanvas = false;

            return true;
        }

        private bool HandleSaveException(Exception ex, string fileName)
        {
            MessageBox.Show(owner,
                "Save File operation failed. File name: " + fileName + "\n" +
                "Reason: " + ex.Message,
                owner.Title);

            error = true;
            return error;
        }
    }
}
